<template>
  <!--文件长传-->
  <div :class="['upload-file',componentSetOptions.class]">
    <el-upload
        ref="upload"
        :action="uploadFileUrl"
        :show-file-list="false"
        list-type="text"
        :auto-upload="true"
        :before-upload="uploadFileUpload"
        :on-error="uploadFileError"
        :on-success="uploadFileSuccess"
        :multiple="componentSetOptions.multiple"
        name="photofile"
        :accept="componentSetOptions.accept"
        :data="uploadFileField"
        :disabled="disabled"
        :file-list="uploadValue2"
        :limit="componentSetOptions.limit"
        :on-exceed="handleExceed"
        :headers="headersData"
    >
      <el-button type="primary">{{ componentSetOptions.name }}</el-button>
    </el-upload>
    <div class="upload-file-box">
      <ul>
        <li
            v-for="(item,key) in uploadValue"
            :key="key"
            @mouseenter="liHoverTrue" @mouseleave="liHoverFalse"
        >
          <i class="el-icon-document"></i>
          <span>{{ item.name }}</span>
          <i class="el-icon-check"></i>
          <i class="el-icon-download" @click="uploadFileDownload(item[componentSetOptions.urlType],item)"></i>
          <i class="el-icon-close" @click="uploadFileDel(key,item)" v-if="!disabled"></i>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>

export default {
  components: {},
  //uploadValue 接收值的字段  componentSetOptions 设置字段
  props: ['componentSetOptions', 'uploadValue','disabled'],
  data() {
    return {
      //附件
      // uploadFileUrl: this.$store.state.env + '/api/common/uploadFile',
      uploadFileUrl: process.env.NODE_ENV === "development" ? `http://localhost:8081/api/frame/upload/uploadFile` :`${this.$store.state.env}/api/frame/upload/uploadFile`,
      headersData: {token: `${window.localStorage.getItem('token')}`}, //上传图片的token
      uploadFileField: {remarks: 1}, //上传添加的字段
      uploadFileName: '', //上传文件成功后文件的名称
      uploadValue2: [],
    };
  },
  mounted() {
  },
  methods: {
    //超过最大限制文件会提示
    handleExceed(files, fileList) {
      console.log(files)
      this.$message.warning(`当前限制选择 ${this.componentSetOptions.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },

    //列表 li鼠标移入
    liHoverTrue(event) {
      event.currentTarget.className = "li-hover"
    },
    //列表 li鼠标移除
    liHoverFalse(event) {
      event.currentTarget.className = ""
    },
    //附件下载
    uploadFileDownload(url, item) {
      //下载不了是跨域的问题
      // const URL = this.$store.state.env + '/' + url
      const URL = url
      // let tmpArr = URL.split('/')
      // let fileName = tmpArr[tmpArr.length - 1]
      window.URL = window.URL || window.webkitURL
      let xhr = new XMLHttpRequest()
      xhr.open('get', URL, true)
      xhr.responseType = 'blob'
      xhr.onload = function () {
        if (this.status == 200) {
          //得到一个blob对象
          let blob = this.response
          let fileUrl = window.URL.createObjectURL(blob)
          let a = document.createElement('a')
          ;(document.body || document.documentElement).appendChild(a)
          a.href = fileUrl
          if ('download' in a) {
            a.download = item.name
          } else {
            a.setAttribute('download', item.name)
          }
          a.target = '_self'
          a.click()
          a.remove()
        }
      }
      xhr.send()
      // window.open(url)
    },
    //附件 移除文件时的钩子
    uploadFileDel(key, item) {
      console.log(item)
      this.$confirm(`确定移除${item.name}？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //附件删除方法
        if (this.componentSetOptions.delMethod) {
          this.HandleUtils.handleParent(this.$parent, this.componentSetOptions.delMethod, item);
        }
        this.uploadValue2.splice(key, 1);
        this.uploadValue.splice(key, 1);
        this.$message({
          type: 'success',
          message: '移除成功!'
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消移除'
        });
      });
    },
    //附件 上传失败的钩子
    uploadFileError() {
      this.$message.error('附件上传失败');
    },
    //附件 上传成功钩子
    uploadFileSuccess(response, file, fileList) {
      this.uploadValue2 = fileList;
      let data = response.map;
      data.name = this.uploadFileName;
      this.uploadValue.push(data)

      // let fileList2 = JSON.parse(JSON.stringify(this.uploadValue2));
      // this.uploadValue.splice(0, this.uploadValue.length);
      // for (let i = 0; i < fileList2.length; i++) {
      //   if (fileList2[i].response) {
      //     let data = fileList2[i].response.data;
      //     data.name = fileList2[i].name
      //
      //   }
      // }
    },
    //附件 上传文件之前的钩子
    uploadFileUpload(file) {
      this.uploadFileName = file.name;//名字存起来，传给后台要用
      const isLt2M = file.size / 1024 / 1024 < this.componentSetOptions.size;
      if (!isLt2M) {
        this.$message.error(`${file.name}文件大小能超过${this.componentSetOptions.size}MB！`);
        return false;
      }
      //
      // const isText = (file.type === 'application/vnd.ms-excel' || file.type === 'application/pdf' ||  file.type === 'application/vnd.ms-powerpoint' || file.type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation');
      // if (!isText) {
      //   this.$message.error('上传附件格式错误!');
      // }
      // return isText;
    },
  },
};
</script>

<style lang="scss" scoped>
//文件上传样式
.upload-file {
  @include flex(nowrap);

  &-box {
    ul {
      @include flex(wrap);

      .li-hover {
        background: $bg-basic;

        i {
          &:nth-of-type(2) {
            display: none;
          }

          &:nth-of-type(3) {
            display: inline-block;

          }

          &:nth-of-type(4) {

            display: inline-block;
          }
        }
      }

      li {
        padding: 5px;
        border-radius: 5px;
        font-size: 14px;
        @include flex();
        cursor: pointer;

        span {
          font-size: 16px;
          margin-right: 8px;
        }

        i {
          font-size: 13px;
          background: #303133;
          border-radius: 50%;
          padding: 3px;
          margin: 0 5px;
          color: #fff;

          &:nth-of-type(1) {
            background: none;
            font-size: 18px;
            color: $color-basic;
          }

          &:nth-of-type(2) {
            background: $color-success;
          }

          &:nth-of-type(3) {
            background: $color-info;
            display: none;
          }

          &:nth-of-type(4) {
            background: $color-danger;
            display: none;
          }
        }
      }
    }
  }
}
</style>
